package com.yonyou.pmclouds.basecom.dao.typehandler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.StringTypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * string类型处理器，避免数据库中存储null值，将null转换为~，如果字符串以~开始，则在开始部分，额外增加一个~
 *
 * @author mapeif
 */
@MappedJdbcTypes(value = {JdbcType.CHAR, JdbcType.VARCHAR}, includeNullJdbcType = true)
public class NonNullStringTypeHandler extends StringTypeHandler {
    public static final String NULL_VALUE_REPLACEMENT = "~";

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getOrigString(super.getNullableResult(rs, columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getOrigString(super.getNullableResult(rs, columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getOrigString(super.getNullableResult(cs, columnIndex));
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        String processed = parameter;
        if (parameter == null) {
            processed = NULL_VALUE_REPLACEMENT;
        } else if (parameter.startsWith(NULL_VALUE_REPLACEMENT)) {
            processed = NULL_VALUE_REPLACEMENT + parameter;
        }
        ps.setString(i, processed);
    }

    private static String getOrigString(String converted) {
        if (converted == null) {
            return null;
        }
        if (converted.startsWith(NULL_VALUE_REPLACEMENT)) {
            if (converted.length() == NULL_VALUE_REPLACEMENT.length()) {
                return null;
            }
            return converted.substring(1);
        }
        return converted;
    }
}
